/*
 * Copyright 2011 Shotaro Uchida
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jazzkaffe;

import java.net.ProtocolException;

/**
 * Abstract ZigBee addressing primitive.
 * @author Shotaro Uchida
 */
public abstract class ZigBeeAddress {

    public static final char ADDRESS_SEPARATOR1 = ':';
    public static final char ADDRESS_SEPARATOR2 = '-';

    private static char addressSeparator = ADDRESS_SEPARATOR1;
    protected int addressSize;
    protected byte[] mac;

    protected ZigBeeAddress(byte[] mac, int addressSize) {
        this.addressSize = addressSize;
        if (mac == null) {
            this.mac = new byte[addressSize];
            for (int i = 0; i < addressSize; i++) {
                this.mac[i] = 0x00;
            }
        } else {
            this.mac = mac;
        }
    }

    protected ZigBeeAddress(String address, int addressSize) throws ProtocolException {
        this.addressSize = addressSize;
        String[] s = Util.split(address, ZigBeeAddress.getAddressSeparator());
        if (s.length != addressSize) {
            throw new ProtocolException("Invalid address.");
        }
        this.mac = new byte[addressSize];
        for (int i = 0; i < addressSize; i++) {
            this.mac[i] = (byte) Integer.parseInt(s[addressSize - 1 - i], 16);
        }
    }
    
    public static char getAddressSeparator() {
        return ZigBeeAddress.addressSeparator;
    }

    public static void setAddressSeparator(char addressSeparator) {
        ZigBeeAddress.addressSeparator = addressSeparator;
    }

    public String toString() {
        String s = "";
        for (int i = 0; i < addressSize; i++) {
            s += getAddressSeparator() + Util.toHexString(mac[i]);
        }
        return s.substring(1);
    }

    public int hashCode() {
        int hash = 7;
        hash = 79 * hash + Util.hashcode(mac);
        return hash;
    }

    public boolean equals(Object obj) {
        if (obj instanceof ZigBeeAddress) {
            ZigBeeAddress target = (ZigBeeAddress) obj;
            if (target.addressSize != this.addressSize) {
                return false;
            }
            for (int i = 0; i < addressSize; i++) {
                if (target.mac[i] != this.mac[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    public byte[] array() {
        return mac;
    }
}
